<template>
  <div
    class=" video clear"
    v-loading="isLoading"
    v-if="!networkError"
  >
    <!-- 播放视频 -->
    <div
      :class="[
        'video__left',
        { 'video__left-hold': !srcs.isexpand },
        { 'video__comment-class': !isNotComment }
      ]"
      :style="videoStyleWidth"
    >
      <!-- 播放 -->
      <div id="player-con" :style="playEnded ? 'width:0;height:0;' : ''"></div>
      <div class="video-countdown" v-if="liveStreamStop" style="min-height: 150px;">
        <span>正在接入直播，请稍候刷新界面重试！</span>
      </div>
      <!-- 直播倒计时 -->
      <div class="video-countdown" v-if="!canplay && !playEnded && !liveStreamStop" >
        <span v-html="countDownTime"></span>
      </div>
      <!-- 视频信息 -->
      <div class="item-tit">
        <i class="icon-tit" v-if="classInfo.subjectName">
          {{ classInfo.subjectName.substr(0, 1) }}
        </i>
        {{ classInfo.courseName || classInfo.videoName }}
      </div>
      <div class="item-info" v-if="classInfo">
        {{ classInfo.truename || classInfo.teacherName }}（{{
          classInfo.orgName
        }}） &nbsp;&nbsp;&nbsp;&nbsp;
        <span class="date">{{ classInfo.liveStart | tranTimestamp }}</span>
        <!-- 观看 点赞 收藏 -->
        <template
          v-for="(item, index) in operateList"
          v-if="
            ((playingVideo.videoType == '1' && index == 1) ||
              playingVideo.videoType != '1') &&
              isNotComment
          "
        >
          <span
            class="operate"
            :style="{ color: item.click ? item.color : '' }"
            @click.prevent="clsChange(item)"
          >
            <hf-icon
              size="28px"
              :href="item.click ? item.brightCls : item.cls"
            ></hf-icon>
            {{ item.count }}
          </span>
        </template>
      </div>
      <!-- 视频信息 end -->
    </div>
    <!-- 收起、展开 -->
    <div class="video__collapse" v-if="isNotComment && !noVideoUrl">
      <img
        ref="collapse"
        :src="srcs.isexpand ? srcs.close : srcs.expand"
        @mouseenter="collapseMouseenter"
        @mouseleave="collapseMouseleave"
        @click.prevent="collapseClick()"
      />
    </div>
    <!-- 视频列表 -->
    <div
      v-if="isNotComment"
      :class="srcs.isexpand ? 'video__right' : 'video__right-hold'"
    >
      <div class="vd-list" v-if="videoList.length > 0">相关视频</div>
      <div class="vd-list" v-else>暂无相关视频</div>
      <div class="vd-content">
        <div
          class="item clear"
          v-if="videoList.length > 0"
          v-for="video in videoList"
          :key="video.VideoId"
          @click.prevent="playVideo(video)"
        >
          <div class="img-wrap">
            <img :src="video.coverPath" @error="imgUrlError" />
            <span class="video-status" v-if="video.videoType == '1'">
              直播中
            </span>
            <!-- <div class="vd-cover"></div> -->
          </div>
          <div class="con-wrap">
            <p class="title">{{ video.videoName }}</p>
            <p class="author">{{ video.teacherName }}</p>
            <p class="address">{{ video.orgName }}</p>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class=" video" v-else>
        <!-- <no-record :networkError="networkError" /> -->
  </div>
</template>
<script>
/**
 * 视频详情组件
 */


// 图片地址（样式）
const srcs = {
  isexpand: true,
  close: require('../../assets/video/close.png'),
  closeLight: require('../../assets/video/close_light.png'),
  expand: require('../../assets/video/expand.png'),
  expandLight: require('../../assets/video/expand_light.png')
};

export default {
  name: 'video-detail',
  props: {
    /** 视频id */
    id: {
      type: String,
      // required: true,
    },
    /** 不是评课议课 */
    isNotComment: {
      type: Boolean,
      default: true,
    },
    /** 评课状态 */
    commentStatus: {
      type: String,
    },
    /** 课程信息 */
    classInfo: {
      type: Object,
    }
  },
  data() {
    return {
      isLoading: true,
      networkError: false,
      /** 不存在视频地址 */
      noVideoUrl: true,
      /** 视频可以播放 */
      canplay: false,
      /** 视频播放已结束 */
      playEnded: false,
      /** 直播中断 */
      liveStreamStop: false,
      /** 图片地址（样式） */
      srcs: srcs,
      /** 视频列表 */
      videoList: [],
      /** 观看-点赞-收藏 */
      operateList: [
			  {
				id: 0,
				name: 'view',
				cls: 'icon-guankanrenshu',
				brightCls: 'icon-guankanrenshu',
				click: false,
				color: '',
				count: 0,
			  },
			  {
				id: 1,
				name: 'favor',
				cls: 'icon-dianzan',
				brightCls: 'icon-yidianzan',
				click: false,
				color: '#FF583A',
				count: 0,
			  },
			  {
				id: 2,
				name: 'collection',
				cls: 'icon-shoucang',
				brightCls: 'icon-yishoucang',
				click: false,
				color: '#FFAE30',
				count: 0,
			  },
			],
      /** 创建Aliplayer */
      player: null,
      /* 正在播放的视频资源 */
      playingVideo: {
        subjectName: '',
        videoType: 1, // 0：点播 1：直播
      },
      /** 用户Id */
      userId: '1111',
      /** 定时器 */
      mySetTimeout: null,
      /** 倒计时 */
      countDownTime: '......',
    };
  },
  computed: {
    /** video的宽度 */
    videoStyleWidth() {
      return this.isNotComment ? '' : 'width: 100%;';
    },
    /** 当前时间戳 */
    timestamp() {
      return new Date().getTime();
    },
  },
  methods: {
    getCountDown() {
      let self = this;

      // 小于五分钟倒计时
      let ss = () => {
        let timer = setInterval(function () {
          let startTime = new Date().getTime();
          let endTime = self.playingVideo.liveStart;
          let t = endTime - startTime;
          if (t > 0) {
            let day = Math.floor(t / 86400000);
            let hour = Math.floor((t / 3600000) % 24);
            let min = Math.floor((t / 60000) % 60);
            let sec = Math.floor((t / 1000) % 60);
            hour = hour < 10 ? "0" + hour : hour;
            min = min < 10 ? "0" + min : min;
            sec = sec < 10 ? "0" + sec : sec;
            let format = '';
            if (day <= 0 && hour <= 0 && min <= 5) {
              format = `课程即将开始<br/><span style="font-size:60px;">${min}分${sec}秒</span>`;
            }
            self.countDownTime = format;
          } else {
            clearInterval(timer);
            self.countDownTime = '正在接入直播，请耐心等待';

            // 创建播放器
            let data = self.playingVideo;
            if(data && data.videoType==='0'){
              // 点播
              self.createDemoPlayer(data.videoUrl, data.coverPath);
            }else{
              // 直播
              if (!data.videoUrl) {
                self.getVideoDetail(true);
              } else {
                let isiOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
                self.createLiveVideoPlayer(isiOS ? data.muUrl : data.muUrl, data.coverPath);
              }
            }

          }
        }, 1000);
      }

      // 刚进页面的时间戳
      let nowTime = new Date().getTime();
      // 倒计时5分钟的时间戳
      let canCountDownTime = self.playingVideo.liveStart;
      let diffTime = canCountDownTime - nowTime;
      // 大于5分钟不倒计时
      if (diffTime > 300000) {
        self.countDownTime = `直播时间<br/>${self.$options.filters.tranTimestamp(self.playingVideo.liveStart, true)}<br/>敬请期待`;
        setTimeout(() => {
          ss();
        }, diffTime);
      } else {
        ss();
      }
    },
    /** 图片地址出错 */
    imgUrlError(e) {
      // e.target.src = require('../../assets/images/imgUrlError.png');
    },
    /** 数据正在加载中... */
    dataloading() {
      this.isLoading = true;
    },
    /** 数据请求成功 */
    dataloadedSuccess() {
      this.isLoading = false;
      this.networkError = false;
    },
    /** 数据请求失败-网络问题 */
    dataloadedFail() {
      this.isLoading = false;
      this.networkError = true;
    },
    // 点击列表播放某个视频 {Object} video 播放视频的资源 */
    playVideo(video) {
      this.$emit('changeRouterPath', video);
    },
    /**
     * 创建播放器
     * @param {String} source 视频地址
     * @param {String} cover  视频封面图
     */
    createDemoPlayer(source, cover) {
      // 初始化
      let props = {
        url: source,
        // url: 'http://ivi.bupt.edu.cn/hls/hunanhd.m3u8',
        container: document.getElementById("player-con"),
        autoplay: true,
        poster: cover,
      };
      this.playEnded = false;
      this.canplay = false;
      const _this = this;
      // 判断直播点播
      if (this.playingVideo.videoType == '1') {
        props.isLive = true;
      }

      // 创建
      this.player = new QPlayer(props);

      // 监听
      this.player.on('ready', function (e) {
        console.log('创建成功');
      });
      this.player.on('playing', function (e) {
        _this.canplay = true;
        console.log('正在播放');
      });
      this.player.on('canplay', function (e) {
        _this.canplay = true;
        console.log('canplay');
      });
      this.player.on('error', function (err) {
        console.log('error' + err);
      });
      this.player.on('ended', function (err) {
        console.log('ended' + err);
      });
    },

    createLiveVideoPlayer(source, cover) {
      // 初始化
      this.playEnded = false;
      this.canplay = false;
      this.liveStreamStop = false;
      const _this = this;

      const props = {
        id: 'player-con',
        source: source,
        width: '100%',
        height: '485px',
        autoplay: true,
        isLive: true,
        rePlay: false,
        showBuffer: true,
        snapshot: false,
        showBarTime: 5000,
        useFlashPrism: false,
        skinLayout: [
          { name: 'bigPlayButton', align: 'blabs', x: 30, y: 80 },
          { name: 'errorDisplay', align: 'tlabs', x: 0, y: 0 },
          { name: 'infoDisplay', align: 'cc' },
          {
            name: 'controlBar',
            align: 'blabs',
            x: 0,
            y: 0,
            children: [
                { name: 'liveDisplay', align: 'tlabs', x: 15, y: 25 },
                { name: 'fullScreenButton', align: 'tr', x: 10, y: 25 },
                { name: 'volume', align: 'tr', x: 10, y: 25 },
            ],
          },
        ],
      }

      // 创建
      this.player = new Aliplayer(props);

      // 监听
      this.player.on('ready', function (e) {
        console.log('创建成功');
      });
      this.player.on('playing', function (e) {
        _this.canplay = true;
        this.liveStreamStop = false;
        console.log('正在播放');
      });
      this.player.on('onM3u8Retry', function (e) {
         _this.liveStreamStop = true;
         _this.canplay = false;
        console.log('直播方离开请稍等...');
      });
      this.player.on('liveStreamStop', function (e) {
          _this.liveStreamStop = true;
         _this.canplay = false;
        console.log('直播中断或结束');
      });
      this.player.on('canplay', function (e) {
        _this.canplay = true;
        _this.playEnded = false;
        this.liveStreamStop = false;
        console.log('canplay');
      });
      this.player.on('error', function (err) {
        console.log(err);
      });
      this.player.on('ended', function (e) {
        console.log('播放已结束');
      });
      this.player.on('pause', function (e) {
        console.log('pause');
      });
      this.player.on('play', function (e) {
        this.liveStreamStop = false;
        console.log('开始播放');
      });
    },

    /**  折叠右边视频列表点击事件 */
    collapseClick() {
      this.srcs.isexpand = !this.srcs.isexpand;
      if (this.srcs.isexpand) {
        this.$refs.collapse.src = srcs.closeLight;
      } else {
        this.$refs.collapse.src = srcs.expandLight;
      }
    },
    /**  鼠标移入-修改src属性 */
    collapseMouseenter() {
      if (this.srcs.isexpand) {
        this.$refs.collapse.src = srcs.closeLight;
      } else {
        this.$refs.collapse.src = srcs.expandLight;
      }
    },
    /**  鼠标移出-修改src属性 */
    collapseMouseleave() {
      if (this.srcs.isexpand) {
        this.$refs.collapse.src = srcs.close;
      } else {
        this.$refs.collapse.src = srcs.expand;
      }
    },
    /**  观看-点赞-收藏，点击事件 {Object} item 当前点击的数据 */
    clsChange(item) {
      if (item.name == 'view') {
        return;
      }
      // 点亮 + -1
      this.operateList[item.id].click = !item.click;
      if (this.operateList[item.id].click) {
        this.operateList[item.id].count++;
      } else {
        this.operateList[item.id].count--;
      }
      // 调接口
      switch (item.name) {
        case 'favor':
          this.setVideoFavorAdd(item); // 点赞
          break;
        case 'collection':
          this.setVideoCollectionAdd(item); // 收藏
          break;
        default:
          break;
      }
    },
    /**  点播资源点赞 {Object} item 当前点击的数据 */
    setVideoFavorAdd(item) {
      const params = {
        resourceId: this.playingVideo.id,
        userId: this.userId
      };
      //this.apiName.setVideoFavorAdd(params);
    },
    /**  点播资源收藏 {Object} item 当前点击的数据 */
    setVideoCollectionAdd(item) {
      const params = {
        resourceId: this.playingVideo.id,
        userId: this.userId
      };
      // const data = await this.apiName.setVideoCollectionAdd(params);
    },
    /**  点播资源观看 */
    setVideoViewAdd() {
      const params = {
        resourceId: this.playingVideo.id,
        userId: this.userId
      };
      // const data = await this.apiName.setVideoViewAdd(params);
    },
    /**  获取视频详情 {Boolean} decycle 是否循环 */
    getVideoDetail(decycle) {
      this.noVideoUrl = true;
      const data = {
					"collectionCount":2,
					"coverPath":"http://reclass.yunhf.com.cn/WX20200224-104418.png",
					"createdDt":1582597261000,
					"dateTime":1594173017000,
					"favorCount":13,
					"fileGroupId":"25079801341251412",
					"gradeId":"1",
					"gradeName":"一年级",
					"id":"1227132663211589633",
					"isCollection":false,
					"isFavor":false,
					"liveEnd":1582597440000,
					"liveStart":1582597440000,
					"orgName":"机构名",
					"segmentId":"0",
					"status":1,
					"subjectId":"LANGUAGE",
					"subjectName":"语文",
					"teacherName":"11",
					"videoName":"视步名",
					"videoType":"0",
					"videoUrl":"http://reclass2.yunhf.com.cn/hfv4.mp4",
					"viewCount":76
				};
 
      // 请求成功
      this.playingVideo = data;
      let nowTime = new Date().getTime();

      // 不存在视频地址
      if (data.videoUrl) {
        this.noVideoUrl = false;
      }

		this.operateList[0].count = data.viewCount;
		this.operateList[1].count = data.favorCount;
		this.operateList[1].click = data.isFavor;
		this.operateList[2].count = data.collectionCount;
		this.operateList[2].click = data.isCollection;
		// 视频列表、观看加一
		this.$nextTick(() => {
		  this.getList();
		  this.setVideoViewAdd();
		});
    },
    /**  获取视频列表 */
    getList() {
      const params = {
        resId: this.playingVideo.id,
        gradeId: this.playingVideo.gradeId,
        subjectId: this.playingVideo.subjectId,
        videoType: this.playingVideo.videoType
      };
      this.dataloading();
	  // 屏蔽请求：/video/relatedList
      const data = [];
      // 请求成功
      this.videoList = data || [];
      this.dataloadedSuccess();
    },
 
    async init() {
      if (this.id === ' ') {
        this.isLoading = false;
        return;
      }
      await this.getVideoDetail();
      await this.getCountDown();
    }
  },
  beforeDestroy() {
    //如果定时器在运行则关闭
    clearTimeout(this.mySetTimeout);
  },
  created() {
    this.init();
  },
  mounted() {
    this.$nextTick(() => { });
  }
};
</script>
<style lang="scss">
.clear::before,
.clear::after {
  content: "";
  clear: both;
  visibility: hidden;
  font-size: 0;
  height: 0;
}
// 视频自定义
.prism-player {
  max-height: 478px;
}
.prism-player .prism-controlbar {
  background: linear-gradient(
    180deg,
    rgba(0, 0, 0, 0) 0%,
    rgba(0, 0, 0, 0.8) 100%
  );
  height: 60px;
}
.prism-player .prism-controlbar .prism-controlbar-bg {
  background: transparent;
  height: 60px;
}
.prism-player .prism-liveshift-progress,
.prism-player .prism-progress {
  left: 168px !important;
  top: 23px;
  width: 565px;
}
.prism-fullscreen .prism-liveshift-progress,
.prism-fullscreen .prism-progress {
  width: 84% !important;
}
.prism-player .prism-thumbnail {
  margin-left: 136px !important;
}
.prism-player .prism-progress .prism-progress-played,
.prism-player .prism-volume-control .volume-value,
.prism-player .prism-volume-control .volume-cursor,
.prism-player .prism-volume-control .volume-cursor:hover {
  background-color: #ff7000;
}
.prism-player .prism-progress .prism-progress-cursor {
  background: none;
  background-color: #ff7000;
}
.prism-player .prism-progress .prism-progress-cursor img {
  width: 0;
  height: 0;
}
.prism-player .prism-volume-control {
  background: transparent;
  box-shadow: none;
}
.prism-player .prism-volume-control .volume-range {
  background-color: #73777a;
}
.prism-player .prism-info-display {
  width: 827px;
}
.prism-player .prism-volume .volume-icon {
  background: url("../../assets/video/volume.png");
  background-size: contain;
}
.prism-player .prism-fullscreen-btn {
  background: url("../../assets/video/fullscreen.png") no-repeat;
  background-size: contain;
}
.prism-player .prism-volume .volume-icon .short-horizontal,
.prism-player .prism-volume .volume-icon .long-horizontal {
  display: none;
}
.prism-ErrorMessage,
.operators {
  display: none !important;
}
.video {
  height: 581px;
  width: 1200px;
  margin-top: 24px;
  margin-bottom: 16px;
  // padding: 24px 0 24px 24px;
  padding: 24px;
  background-color: #ffffff;
  overflow: hidden;
  border-radius: 5px;
  .norecord {
    background-color: #eeeeee !important;
    margin: 0;
    padding-bottom: 50px;
  }
  .video__error {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    width: 850px;
    height: 485px;
    color: #ffffff;
    text-align: center;
    line-height: 485px;
    background: black;
    font-size: 16px;
  }
  .video__left {
    position: relative;
    float: left;
    width: 850px;
    .icon-tit {
      display: inline-block;
      width: 22px;
      height: 22px;
      margin-right: 5px;
      border-radius: 1px;
      font-size: 17px;
      line-height: 23px;
      text-align: center;
      font-style: normal;
      vertical-align: top;
      color: #ffffff;
      background: #f5a623;
      font-weight: normal;
    }
    .item-tit {
      color: #333333;
      font-size: 20px;
      margin: 19px 0 8px 0;
      line-height: 20px;
      font-weight: bold;
    }
    .item-info {
      color: #333333;
      line-height: 14px;
      .date {
        color: #999999;
        margin-right: 28px;
      }
      .operate {
        margin-right: 21px;
        cursor: pointer;
      }
    }
    .item-tit,
    .item-info {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    #player-con {
      width: 850px;
      height: 478px;
    }
    .video-countdown {
      position: absolute;
      top: 0;
      left: 0;
      bottom: 76px;
      right: 0;
      background: url('../../assets/video/bg_video.png');
      background-repeat: no-repeat;
    }
    .video-countdown {
      text-align: center;
      padding-top: 177px;
      font-size: 24px;
      color: #ffffff;
    }
  }
  .video__left-hold {
    float: left;
    width: 100%;
    .prism-player .prism-liveshift-progress,
    .prism-player .prism-progress {
      width: 895px;
    }
    #player-con {
      width: 100%;
    }
  }
  .video__comment-class {
    .prism-player .prism-liveshift-progress,
    .prism-player .prism-progress {
      width: 915px;
    }
  }
  .video__collapse {
    height: 100%;
    float: left;
    width: 0;
    margin-top: 226px;
    img {
      cursor: pointer;
    }
  }

  .video__right {
    float: right;
    width: 309px;
    .vd-list {
      font-size: 16px;
      letter-spacing: 0;
      text-align: left;
      margin-bottom: 14px;
      line-height: 16px;
      color: #333333;
    }
    .vd-content {
      height: 454px;
      overflow-y: scroll;
      .item {
        width: 100%;
        height: 78px;
        margin-bottom: 12px;
        cursor: pointer;
      }
      .img-wrap {
        float: left;
        height: 78px;
        position: relative;
        width: 135px;
        img {
          display: block;
          width: 135px;
          height: 78px;
        }
        .video-status {
          position: absolute;
          top: 4px;
          right: 4px;
          display: inline-block;
          width: 42px;
          height: 16px;
          border-radius: 3px;
          font-size: 10px;
          text-align: center;
          background-color: #dfb371;
          color: #ffffff;
          font-style: normal;
        }
        .vd-cover {
          position: absolute;
          display: none;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(0, 0, 0, 0.8) url("../../assets/video/play.png")
            center center no-repeat;
          background-size: 22px 22px;
        }
        &:hover {
          .vd-cover {
            display: block;
          }
        }
      }
      .con-wrap {
        width: 140px;
        float: right;
        margin-right: 10px;
        overflow: hidden;
        .title {
          width: 100%;
          height: 40px;
          font-size: 14px;
          color: #333333;
          letter-spacing: 0;
          line-height: 18px;
          text-align: left;
          white-space: normal;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
        .author,
        .address {
          color: #999999;
          font-size: 12px;
          letter-spacing: 0;
          margin-top: 3px;
          text-align: left;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
        }
      }
    }
  }
  .video__right-hold {
    float: right;
    width: 0;
    overflow: hidden;
  }
  @media (max-width: 768px) {
    .player-demo .main-content {
      width: 100%;
      padding: 0 20px;
    }
    .player-demo .main-content .m-left {
      width: 100%;
    }
    .player-demo .main-content .m-right {
      width: 100%;
    }
    .player-demo .main-content .m-right .vd-content .con-wrap {
      width: 185px;
    }
  }
}
</style>


